<?php

namespace app\api\controller;

use app\common\controller\Api;
use \think\Validate;

/**
 * 预约接口
 * 
 * 支持通过项目ID对象数组提交预约信息，支持多个项目及数量
 */
class Subscribe extends Api
{
    protected $noNeedLogin = ['createSubscribe', 'test'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
        
        if (isset($_SERVER['HTTP_ORIGIN'])) {
            header('Access-Control-Expose-Headers: __token__');
        }
        //跨域检测
        check_cors_request();
    }

    /**
     * 创建预约
     * @ApiMethod (POST)
     * @ApiParams (name="clinicname", type="string", required=true, description="诊所名称")
     * @ApiParams (name="itemids", type="array", required=true, description="项目ID对象数组，格式：[{id:1,count:10},{id:2,count:5}]")
     * @ApiParams (name="totalprice", type="decimal", required=true, description="总价格")
     * @ApiParams (name="date", type="string", required=true, description="预约日期，格式：Y-m-d")
     * @ApiParams (name="time", type="string", required=true, description="预约时间，格式：H:i")
     * @ApiParams (name="firstname", type="string", required=true, description="名字")
     * @ApiParams (name="email", type="string", required=true, description="邮箱")
     */
    public function createSubscribe()
    {
        // 获取请求参数
        $data = $this->request->post();
        
        // 手动验证必填参数
        if (empty($data['clinicname'])) {
            $this->error('诊所名称不能为空');
        }
        if (empty($data['itemids']) || !is_array($data['itemids']) || count($data['itemids']) == 0) {
            $this->error('项目ID数组不能为空');
        }
        
        // 验证项目ID对象数组格式
        foreach ($data['itemids'] as $item) {
            if (!is_array($item) || !isset($item['id']) || !isset($item['count'])) {
                $this->error('项目数据格式错误，应为{id:数字,count:数字}格式');
            }
            if (!is_numeric($item['id']) || $item['id'] <= 0) {
                $this->error('项目ID必须是大于0的数字');
            }
            if (!is_numeric($item['count']) || $item['count'] < 0) {
                $this->error('项目数量必须是非负整数');
            }
        }
        
        if (empty($data['totalprice']) || !is_numeric($data['totalprice']) || $data['totalprice'] < 0) {
            $this->error('总价格必须是大于等于0的数字');
        }
        if (empty($data['date']) || !strtotime($data['date'])) {
            $this->error('预约日期格式不正确');
        }
        if (empty($data['time']) || !preg_match('/^([01]?[0-9]|2[0-3]):[0-5][0-9]$/', $data['time'])) {
            $this->error('预约时间格式不正确，应为HH:MM格式');
        }
        if (empty($data['firstname'])) {
            $this->error('名字不能为空');
        }
        if (empty($data['email']) || !filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
            $this->error('邮箱格式不正确');
        }
        
        try {
            // 检查预约日期是否为未来日期
            $appointmentDate = strtotime($data['date']);
            if ($appointmentDate < strtotime(date('Y-m-d'))) {
                $this->error('预约日期不能是过去的日期');
            }
            
            // 准备预约数据 - 处理所有可能的字段
            $subscribeData = [
                'clinicname' => $data['clinicname'],
                'totalprice' => $data['totalprice'],
                'date' => $data['date'],
                'time' => $data['time'],
                'firstname' => $data['firstname'],
                'email' => $data['email'],
                // 项目ID对象数组 - 转换为JSON字符串存储
                'itemids' => json_encode($data['itemids'], JSON_UNESCAPED_UNICODE),
                // 其他可选字段
                'lastname' => isset($data['lastname']) ? $data['lastname'] : '',
                'phone' => isset($data['phone']) ? $data['phone'] : '',
                'address' => isset($data['address']) ? $data['address'] : '',
                'message' => isset($data['message']) ? $data['message'] : '',
            ];
            
            // 记录调试信息
            \think\Log::info('预约数据: ' . json_encode($subscribeData));
            
            // 检查数据库连接
            try {
                $db = \think\Db::name('subscribe');
                \think\Log::info('数据库连接成功');
            } catch (\Exception $e) {
                \think\Log::error('数据库连接失败: ' . $e->getMessage());
                $this->error('数据库连接失败');
            }
            
            // 检查表是否存在
            try {
                $tableExists = $db->query('SHOW TABLES LIKE "subscribe"');
                \think\Log::info('表检查结果: ' . json_encode($tableExists));
            } catch (\Exception $e) {
                \think\Log::error('表检查失败: ' . $e->getMessage());
                $this->error('表检查失败');
            }
            
            // 插入数据
            $result = $db->insert($subscribeData);
            \think\Log::info('插入结果: ' . ($result ? '成功' : '失败'));
            
            if ($result) {
                $id = $db->getLastInsID();
                
                // 直接返回JSON，绕过success方法
                $result = [
                    'code' => 1,
                    'msg' => '预约创建成功',
                    'time' => time(),
                    'data' => [
                        'id' => (int)$id,
                        'clinicname' => (string)$data['clinicname'],
                        'itemids' => (string)$subscribeData['itemids'],
                        'totalprice' => (float)$data['totalprice'],
                        'date' => (string)$data['date'],
                        'time' => (string)$data['time'],
                        'firstname' => (string)$data['firstname'],
                        'email' => (string)$data['email'],
                        'lastname' => isset($data['lastname']) ? (string)$data['lastname'] : '',
                        'phone' => isset($data['phone']) ? (string)$data['phone'] : '',
                        'address' => isset($data['address']) ? (string)$data['address'] : '',
                        'message' => isset($data['message']) ? (string)$data['message'] : '',
                    ]
                ];
                
                header('Content-Type: application/json');
                echo json_encode($result);
                exit;
            } else {
                $this->error('预约创建失败');
            }
            
        } catch (\Exception $e) {
            // 记录错误日志
            \think\Log::error('创建预约失败: ' . $e->getMessage());
            \think\Log::error('错误详情: ' . $e->getTraceAsString());
            
            $this->error('预约创建失败');
        }
    }

    /**
     * 测试接口 - 检查数据库连接和表结构
     */
    public function test()
    {
        $data = [
            'message' => '测试接口正常',
            'timestamp' => date('Y-m-d H:i:s'),
            'php_version' => PHP_VERSION,
            'framework' => 'ThinkPHP',
            'note' => '已更新为使用项目ID对象数组格式'
        ];
        
        $this->success('测试成功', $data);
    }

    /**
     * 接口使用说明
     * 
     * 新的预约接口支持通过itemids对象数组提交项目ID和数量：
     * 
     * 请求示例：
     * {
     *   "clinicname": "诊所名称",
     *   "itemids": [
     *     {"id": 1, "count": 10},
     *     {"id": 2, "count": 5},
     *     {"id": 3, "count": 8}
     *   ],
     *   "totalprice": 100.00,
     *   "date": "2024-01-15",
     *   "time": "14:30",
     *   "firstname": "张三",
     *   "email": "zhangsan@example.com"
     * }
     * 
     * 注意：
     * - itemids必须是对象数组格式，每个对象包含id和count字段
     * - id必须是大于0的数字
     * - count必须是大于0的数字
     * - 项目数据会以JSON字符串格式存储在数据库中
     */
}
